<template>
  <view class="container">
    <!-- 状态栏占位 -->
    <view :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-back" @click="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <text class="nav-title">订单提交成功</text>
      <view class="nav-right"></view>
    </view>
    
    <!-- 成功信息 -->
    <view class="success-section">
      <view class="success-icon">
        <uni-icons type="checkmarkempty" size="60" color="#FF8C42"></uni-icons>
      </view>
      <view class="success-title">订单提交成功</view>
      <view class="success-desc">您的订单已支付成功，商家正在处理中</view>
      <view class="order-no">订单号: {{ orderNo }}</view>
    </view>
    
    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button class="action-btn outline-btn" @click="goToOrderDetail">查看订单</button>
      <button class="action-btn primary-btn" @click="goToHome">返回首页</button>
    </view>
    
    <!-- 推荐商品 -->
    <view class="recommend-section" v-if="recommendProducts.length > 0">
      <view class="section-title">
        <text>猜你喜欢</text>
      </view>
      <view class="recommend-list">
        <view 
          class="recommend-item" 
          v-for="item in recommendProducts" 
          :key="item.id"
          @click="goToProductDetail(item.id)"
        >
          <image class="recommend-image" :src="imageFullUrl(item.mainImageUrl)" mode="aspectFill"></image>
          <view class="recommend-name">{{ item.name }}</view>
          <view class="recommend-price">¥{{ parseFloat(item.price).toFixed(2) }}</view>
          <view class="recommend-add" @click.stop="quickAddToCart(item)">
            <uni-icons type="plus" size="18" color="#fff"></uni-icons>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-section" v-if="isLoadingRecommend">
      <view class="loading-text">正在为您推荐商品...</view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getImageUrl } from '@/config/env';
import { useProductStore } from '@/store/product.js';
import { useCartStore } from '@/store/cart';
import { useUserStore } from '@/store/user';
//import { getCurrentPages } from '@dcloudio/uni-app';

// 状态栏高度
const statusBarHeight = ref(0);
const orderNo = ref('');
const isLoadingRecommend = ref(false);

// 引入状态管理
const productStore = useProductStore();
const cartStore = useCartStore();
const userStore = useUserStore();

// 生成完整的图片 URL - 使用统一的工具函数
const imageFullUrl = getImageUrl;

// 推荐商品列表
const recommendProducts = ref([]);

// 获取推荐商品 - 复用购物车页面的逻辑
const fetchRecommendProducts = async () => {
  isLoadingRecommend.value = true;
  
  try {
    // 确保商品数据已加载
    if (!productStore.products || productStore.products.length === 0) {
      await productStore.fetchProducts();
    }
    
    const allProducts = productStore.products;
    if (allProducts && allProducts.length > 0) {
      // 获取购物车中的商品ID（如果用户已登录）
      let cartProductIds = [];
      if (userStore.isLoggedIn && cartStore.cartItems) {
        cartProductIds = cartStore.cartItems.map(item => item.productId);
      }
      
      // 过滤掉已经在购物车中的商品，只显示可用商品
      const availableProducts = allProducts.filter(product => 
        !cartProductIds.includes(product.id) && 
        product.status !== 0 && 
        product.totalStock > 0
      );
      
      let selectedProducts = [];
      if (availableProducts.length > 0) {
        // 随机打乱数组顺序
        const shuffled = [...availableProducts].sort(() => 0.5 - Math.random());
        // 取前6个商品用于展示
        selectedProducts = shuffled.slice(0, Math.min(6, shuffled.length));
      } else {
        // 如果没有可用商品，就使用所有商品（排除下架商品）
        const validProducts = allProducts.filter(product => product.status !== 0);
        if (validProducts.length > 0) {
          const shuffled = [...validProducts].sort(() => 0.5 - Math.random());
          selectedProducts = shuffled.slice(0, Math.min(6, shuffled.length));
        }
      }
      
      recommendProducts.value = selectedProducts;
      console.log('推荐商品加载成功:', selectedProducts.length, '个商品');
    } else {
      console.log('没有可用的商品数据');
    }
  } catch (error) {
    console.error('获取推荐商品失败:', error);
    uni.showToast({
      title: '推荐商品加载失败',
      icon: 'none'
    });
  } finally {
    isLoadingRecommend.value = false;
  }
};

// 快速添加到购物车
const quickAddToCart = async (product) => {
  if (!userStore.isLoggedIn) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }
  
  try {
    const result = await cartStore.addToCart(product, 1);
    if (result) {
      uni.showToast({
        title: '已添加到购物车',
        icon: 'success'
      });
      // 重新获取推荐商品，移除已添加的商品
      fetchRecommendProducts();
    }
  } catch (error) {
    console.error('快速添加到购物车失败:', error);
    uni.showToast({
      title: '添加失败，请重试',
      icon: 'none'
    });
  }
};

// 获取状态栏高度
const getStatusBarHeight = () => {
  try {
    const systemInfo = uni.getSystemInfoSync();
    statusBarHeight.value = systemInfo.statusBarHeight || 0;
  } catch (e) {
    console.error('获取系统信息失败:', e);
    statusBarHeight.value = 0;
  }
};

// 返回上一页
const goBack = () => {
  goToHome();
};

// 跳转到订单详情
const goToOrderDetail = () => {
  uni.redirectTo({
    url: `/pages/orders/order-detail?orderNo=${orderNo.value}`
  });
};

// 跳转到首页
const goToHome = () => {
  uni.redirectTo({
    url: '/pages/index/index'
  });
};

// 跳转到商品详情
const goToProductDetail = (id) => {
  uni.navigateTo({
    url: `/pages/product/detail?id=${id}&t=${Date.now()}`
  });
};

// 获取页面参数
const getPageParams = () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.$page?.options || {};
  
  if (options.orderNo) {
    orderNo.value = options.orderNo;
  } else {
    // 如果没有订单号，生成一个模拟订单号
    orderNo.value = 'ORDER' + Date.now();
  }
};

// 页面加载时执行
onMounted(async () => {
  console.log('订单成功页面已挂载');
  // 获取状态栏高度
  getStatusBarHeight();
  // 获取页面参数
  getPageParams();
  // 初始化用户状态
  userStore.initUserState();
  // 获取推荐商品
  await fetchRecommendProducts();
});
</script>

<style>
.container {
  background-color: #FFF9F2;
  min-height: 100vh;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 88rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #FFE6CC;
  padding: 0 20rpx;
}

.nav-back, .nav-right {
  width: 80rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

/* 成功信息 */
.success-section {
  margin: 40rpx 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 40rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.success-icon {
  margin-bottom: 20rpx;
}

.success-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.success-desc {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.order-no {
  font-size: 26rpx;
  color: #999;
  background-color: #f5f5f5;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
  margin: 40rpx 20rpx;
  gap: 30rpx;
}

.action-btn {
  width: 300rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 28rpx;
  border-radius: 40rpx;
}

.outline-btn {
  background-color: #fff;
  color: #FF8C42;
  border: 1rpx solid #FF8C42;
}

.primary-btn {
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  color: #fff;
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(255, 140, 66, 0.3);
}

/* 推荐商品 */
.recommend-section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  position: relative;
  padding-left: 20rpx;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 30rpx;
  background-color: #FF8C42;
  border-radius: 3rpx;
}

.recommend-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.recommend-item {
  width: 48%;
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: relative;
}

.recommend-image {
  width: 100%;
  height: 300rpx;
  background-color: #f5f5f5;
}

.recommend-name {
  font-size: 26rpx;
  color: #333;
  padding: 10rpx 15rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.recommend-price {
  font-size: 28rpx;
  color: #FF8C42;
  font-weight: bold;
  padding: 0 15rpx 15rpx;
}

.recommend-add {
  position: absolute;
  right: 10rpx;
  bottom: 10rpx;
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: #FF8C42;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 8rpx rgba(255, 140, 66, 0.3);
  transition: all 0.3s ease;
}

.recommend-add:active {
  transform: scale(0.95);
}

/* 加载状态 */
.loading-section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 40rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  text-align: center;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}
</style>